import { V0, Address, AddressType } from "@ctsy/iot-protocol";
import ctwing from "../../iot/drivers/ctwing";
import { timeout } from '@ctsy/common';
import IOTUtils, { get_uint_buffer, get_timestamp } from '../../iot/lib/utils';
import IotValve from '../../iot/classes/IotValve';
import { NBDing } from '../controller/Ctwing';
import { buffer2hex } from "@ctsy/buffer";
import { Context } from "vm";
var step = 1;
const CTWingDriver = new ctwing()
export var NBCommandLists: { Code: number, Data: Buffer }[] = [];
export async function check_nb_confirm(v0: V0, DeviceID: string, ctx: Context) {
    let confirm = new V0()
    confirm.To = v0.From;
    //服务器的地址标识为FFFF
    confirm.From = new Address(AddressType.Logic, 'FFFF')
    confirm.CompanyID = v0.CompanyID;
    confirm.No = v0.No;
    confirm.End = true;
    confirm.ID = v0.ID;
    confirm.WithTime = v0.WithTime;
    confirm.Time = new Date;
    confirm.Next = true;
    if (v0.Confirm) {
        timeout(300).then(() => {
            CTWingDriver.send([
                {
                    Key: DeviceID,
                    Hex: confirm.encode().toString('hex'),
                    Timeout: 0
                }
            ])
        })
    }
    let ml = await IOTUtils.get_model(ctx, IOTUtils.Models.NbMsgLog).add({
        Chan: 'ctwing',
        V: v0.Version,
        CID: v0.CompanyID,
        Control: v0.Control,
        Time: v0.Time,
        Encrypted: v0.Encrypted,
        Confirm: v0.Confirm,
        To: v0.To.Value,
        From: v0.From.Value,
        ID: v0.ID,
        Finish: !v0.Next,
        No: v0.No,
        Length: v0.Data.length,
        Content: v0.Data.toString('hex')
    })
    switch (v0.Control) {
        case 200:
            let nu = new IotValve.UploadData();
            nu.decode(v0.Data, true);
            console.log(nu.explain.join('\r\n'))
            let t = Object.assign(nu);
            t.TempIn = nu.Temperature.In;
            t.TempOut = nu.Temperature.Out;
            t.ELock = nu.Status.ELock;
            t.EUncap = nu.Status.EUncap;
            t.ETempIn = nu.Status.ETempIn;
            t.ETempOut = nu.Status.ETempOut;
            t.EStatus = nu.Status.EStatus;
            t.MLID = ml.MLID;
            t.Status = true;
            t.Time = v0.Time;
            delete t.Temperature
            IOTUtils.get_model(ctx, IOTUtils.Models.NbHot).add(t)
            break;
    }
    console.warn('控制码:' + v0.Control + '确认帧:' + v0.ID, 'Step:' + step)
    if (NBCommandLists.length > 0) {
        let cmd = NBCommandLists.shift();
        if (!cmd) { return; }
        confirm.Control = cmd.Code;
        confirm.Confirm = true;
        confirm.Time = new Date;
        confirm.Next = false;
        confirm.Data = cmd.Data
        CTWingDriver.send([
            {
                Key: DeviceID,
                Hex: confirm.encode().toString('hex'),
                Timeout: 0
            }
        ])
        NBDing.text(`下发命令:${cmd.Code}，内容:${buffer2hex(cmd.Data)}`)
    }
    if (false) {
        await timeout(300);
        switch (step++) {
            case 1:
                confirm.Control = 201;
                confirm.Confirm = true;
                confirm.Time = new Date;
                confirm.Next = true;
                confirm.Data = Buffer.concat([
                    get_uint_buffer(99, 1),
                    get_uint_buffer(get_timestamp('2019-10-15 15:00:00'), 4),
                    get_uint_buffer(get_timestamp('2020-05-01 08:00:05'), 4),
                ])
                CTWingDriver.send([
                    {
                        Key: DeviceID,
                        Hex: confirm.encode().toString('hex'),
                        Timeout: 0
                    }
                ])
                break;
            case 2:
                confirm.Control = 202;
                confirm.Confirm = true;
                confirm.Time = new Date;
                confirm.Next = false;
                confirm.Data = Buffer.alloc(0)
                CTWingDriver.send([
                    {
                        Key: DeviceID,
                        Hex: confirm.encode().toString('hex'),
                        Timeout: 0
                    }
                ])
                break;
            case 3:
                try {
                    let conf = new IotValve.Config()
                    conf.Black = 1000;
                    conf.Cycle = 100;
                    conf.STime = '2020-01-01 00:00:00';
                    conf.Rand = 250;
                    conf.TempCycle = 250;
                    conf.Delay = 250;

                    confirm.Control = 203;
                    confirm.Confirm = true;
                    confirm.Time = new Date;
                    confirm.Next = false;
                    confirm.Data = conf.encode();
                    CTWingDriver.send([
                        {
                            Key: DeviceID,
                            Hex: confirm.encode().toString('hex'),
                            Timeout: 0
                        }
                    ])
                } catch (error) {
                    debugger
                }

                break;
            case 4:
                step = -1;
                let port = 9600;
                confirm.Control = 204;
                confirm.Confirm = true;
                confirm.Time = new Date;
                confirm.Next = false;
                confirm.Data = Buffer.concat([
                    Buffer.from('10.1.1.2'.split('.').map((v) => Number(v).toString().padStart(3, '0')).join('.'), 'ascii'),
                    Buffer.alloc(1, 0x00),
                    Buffer.from(port.toString(), 'ascii'),
                    Buffer.alloc(6 - port.toString().length, 0x00),
                ]);
                CTWingDriver.send([
                    {
                        Key: DeviceID,
                        Hex: confirm.encode().toString('hex'),
                        Timeout: 0
                    }
                ])
                setTimeout(() => {
                    step = 1;
                }, 3000);
                break;
        }
    }
}